const mongoose = require('mongoose');
const md5 = require('md5');

mongoose.connect('mongodb://localhost:27017/user_manage2');

mongoose.connection.on('open',async () => {
    console.log('数据库连接成功')

    const userModel = require('./models/UserModel');

    // 初始化数据
    let res = await userModel.findOne({ username: 'admin' });
    // 判断数据库中是否已经存在admin用户
    if (!res) {
        //添加初始化用户 admin
        userModel.create({
            username: 'admin',
            pwd: md5('111111'), // 对密码进行md5加密
            profile: '/upload/admin.png'
        });

        // 初始化 用户列表 
        for (let i = 0; i < 20; i++) {
            userModel.create({
                username: 'user_' + i,
                pwd: md5('111'), // 对密码进行md5加密
                profile: '/upload/admin.png'
            });
        }
    }
})

mongoose.connection.on('error', () => {
    console.log('数据库连接失败')
})

module.exports = mongoose;